# coding: utf-8
from enum import Enum
from pathlib import Path
from platform import system
from typing import Union

from pydantic import BaseModel, Field

from .public import read, save, load
from ..enums import BrowserTypes, TestCaseFileTypes

if system() == 'Windows':
    allure = 'allure.bat'
else:
    allure = 'allure'
# msg_template = '''
# ## ${project_name} 自动化测试报告\n\n
# > 👤 测试人员: ${tester_name}\n\n
# > 🤖 测试结果: ${result}\n\n
# > ✅ 通过用例: ${passed}\n\n
# > 🔧 失败用例: ${failed}\n\n
# > ❌ 错误用例: ${error}\n\n
# > ⚠️ 跳过用例: ${skipped}\n\n
# > ⌛ 开始时间: ${started_time}\n\n
# > ⏱️ 执行耗时: ${elapsed}\n\n
# > ➡️ [查看详情](${link})
# '''
msg_template = '''
## ${project_name} 自动化测试报告
> 👤 测试人员: ${tester_name}
> 🤖 测试结果: ${result}
> ✅ 通过用例: ${passed}
> 🔧 失败用例: ${failed}
> ❌ 错误用例: ${error}
> ⚠️ 跳过用例: ${skipped}
> ⌛ 开始时间: ${started_time}
> ⏱️ 执行耗时: ${elapsed}
> ➡️ [查看详情](${link})
'''


class AutoTestSetting(BaseModel):
    project_name: str = Field('AutoTestProject', description='项目名称')
    tester_name: str = Field('Tester', description='测试人员名称')
    language: str = Field('zh-CN', description='语言')
    test_case_path: Union[Path, str] = Field(Path.cwd() / 'test_cases', description='测试用例路径')
    allure_app_path: Union[Path, str] = Field(Path.cwd() / f'AppData/allure-2.30.0/bin/{allure}',
                                              description='allure安装路径')
    case_type: Union[str, Enum] = Field(TestCaseFileTypes.YML, description='用例类型')


class RequestSetting(BaseModel):
    timeout: int = Field(60, description='请求超时时间')
    user_agent: str = Field('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                            'Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0', description='请求头中的User-Agent')


class ReportSetting(BaseModel):
    report_dir: Union[Path, str] = Field(Path.cwd() / 'AppData/reports', description='测试报告路径',
                                         alias='测试报告路径')
    log_path: Union[Path, str] = Field(Path.cwd() / f'AppData/Log', description='日志路径')


class BrowserSetting(BaseModel):
    browser: Union[str, Enum] = Field(BrowserTypes.Chromium, description='浏览器名称')


class MinioSetting(BaseModel):
    endpoint: str = Field('', description='Minio服务地址')
    access_key: Union[str, None] = Field(None, description='Minio访问密钥')
    secret_key: Union[str, None] = Field(None, description='Minio安全密钥')
    secure: bool = Field(False, description='是否使用https')
    bucket_name: str = Field('', description='Minio桶名称')
    link_expires: int = Field(7, description='Minio链接有效期（天）')


class DingDingSetting(BaseModel):
    access_token: str = Field('', description='钉钉机器人access_token')
    secret: str = Field('', description='钉钉机器人secret')


class WechatSetting(BaseModel):
    webhook: str = Field('', description='企业微信机器人webhook')


class EmailSetting(BaseModel):
    # 服务器配置
    smtp_host: str = Field('smtp.163.com', description='SMTP服务器地址')
    smtp_port: int = Field(465, description='SMTP服务器端口')
    smtp_user: str = Field('13511111111@163.com', description='SMTP用户名')
    smtp_password: str = Field('QJELFEHEDKGSRJJJ', description='SMTP密码')
    smtp_ssl: bool = Field(True, description='是否使用SSL加密')
    # 收件人配置
    receiver: Union[str, list] = Field(['10086@qq.com'], description='收件人邮箱')


class SettingModel(BaseModel):
    setting_path: Union[Path, str] = Field(Path.cwd() / 'settings.json', description='设置文件路径')
    variables: Union[Path, str] = Field(Path.cwd() / 'AppData/variables', description='全局变量')
    auto_test_setting: AutoTestSetting = Field(AutoTestSetting(), description='自动化测试设置')
    request_setting: RequestSetting = Field(RequestSetting(), description='请求设置')
    browser_setting: BrowserSetting = Field(BrowserSetting(), description='浏览器设置')
    report_setting: ReportSetting = Field(ReportSetting(), description='测试报告设置')
    ding_ding_setting: DingDingSetting = Field(DingDingSetting(), description='钉钉机器人设置')
    minio_setting: MinioSetting = Field(MinioSetting(), description='Minio设置')
    wechat_setting: WechatSetting = Field(WechatSetting(), description='企业微信机器人设置')
    email_setting: EmailSetting = Field(EmailSetting(), description='邮件设置')
    msg_template: str = Field(msg_template, description='消息模板')

    def read(self):
        return read(self)

    def save(self):
        """
        保存设置文件
        :return:
        """
        return save(self, self.setting_path)

    def load(self) -> 'SettingModel':
        """
        加载设置文件
        :return:
        """
        data = load(self.setting_path)
        data1 = self.dict()
        if data:
            data1.update(data)
            return SettingModel(**data1)
        else:
            self.save()
            return self
